//
//  CallingViewController.m
//  CallTelphone
//
//  Created by mac on 2023/5/23.
//

#import "CallinViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "tellCallModel.h"
#import <MediaPlayer/MediaPlayer.h>

@interface CallinViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *icon14ImageView;
@property (weak, nonatomic) IBOutlet UIImageView *icon20ImageView;
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic,assign) int time;
@property (nonatomic,assign) BOOL isMT;
@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumberLabel;
@property (nonatomic,assign) float volume;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (nonatomic, strong)NSTimer *timer;
@property (weak, nonatomic) IBOutlet UIButton *callTelPhoneButton;
@property (weak, nonatomic) IBOutlet UIButton *muteButton;
@property (weak, nonatomic) IBOutlet UIView *telphoneBgView;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber1;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber2;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber3;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber4;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber5;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber6;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber7;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber8;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber9;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber10;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber11;
@property (weak, nonatomic) IBOutlet UIButton *callTelphoneNumber0;
@end

@implementation CallinViewController

//@property (nonatomic,copy) NSString *date;
//@property (nonatomic,copy) NSString *dateTime;
//@property (nonatomic,copy) NSString *to;
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    RE_SINGLETON(CallTelphoneManager).isCalling = NO;
}
- (IBAction)handown:(id)sender {
    tellCallModel *call = [[tellCallModel alloc] init];
    NSArray *list = [tellCallModel retrieveArray];
    call.tID = [NSString stringWithFormat:@"%lu",list.count + 1];
    call.time = self.statusLabel.text;
    call.phone = self.telphoneNumber;
    call.address = @"电话";
    call.dian = @"来电";
    call.timeInterval = [self timeInterval];
    call.dateTime = [self dateTime];
    call.totalSeconds = [NSString stringWithFormat:@"%d",self.time];
    call.isCallIn = @"1";
    [call addToDB];
    
    [self dismissViewControllerAnimated:YES completion:^{
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session removeObserver:self forKeyPath:@"outputVolume"];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([AVAudioSession sharedInstance].outputVolume == 1){
        MPVolumeView *volumeView = [[MPVolumeView alloc] init];
        UISlider* volumeViewSlider = nil;
        for (UIView *view in [volumeView subviews]){
            if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
                volumeViewSlider = (UISlider*)view;
                break;
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [volumeViewSlider setValue:0.7 animated:YES];
            [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
        });
    }
}

- (NSString *)timeInterval{
    NSDate * today = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[today timeIntervalSince1970]];
    return timeSp;
}

- (NSString *)dateTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    NSString *string = [formatter stringFromDate:date];
    return string;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.callTelphoneNumber1.layer.cornerRadius = 40;
    self.callTelphoneNumber1.clipsToBounds = YES;
    self.callTelphoneNumber2.layer.cornerRadius = 40;
    self.callTelphoneNumber2.clipsToBounds = YES;
    self.callTelphoneNumber3.layer.cornerRadius = 40;
    self.callTelphoneNumber3.clipsToBounds = YES;
    self.callTelphoneNumber4.layer.cornerRadius = 40;
    self.callTelphoneNumber4.clipsToBounds = YES;
    self.callTelphoneNumber5.layer.cornerRadius = 40;
    self.callTelphoneNumber5.clipsToBounds = YES;
    self.callTelphoneNumber6.layer.cornerRadius = 40;
    self.callTelphoneNumber6.clipsToBounds = YES;
    self.callTelphoneNumber7.layer.cornerRadius = 40;
    self.callTelphoneNumber7.clipsToBounds = YES;
    self.callTelphoneNumber8.layer.cornerRadius = 40;
    self.callTelphoneNumber8.clipsToBounds = YES;
    self.callTelphoneNumber9.layer.cornerRadius = 40;
    self.callTelphoneNumber9.clipsToBounds = YES;
    self.callTelphoneNumber10.layer.cornerRadius = 40;
    self.callTelphoneNumber10.clipsToBounds = YES;
    self.callTelphoneNumber11.layer.cornerRadius = 40;
    self.callTelphoneNumber11.clipsToBounds = YES;
    self.callTelphoneNumber0.layer.cornerRadius = 40;
    self.callTelphoneNumber0.clipsToBounds = YES;
    [self resetTelphoneNumberHidden:YES];
        
    self.phoneNumberLabel.text = self.telphoneNumber;
    self.telphoneBgView.hidden = YES;
//    self.telphoneBgImageView.transform = CGAffineTransformMakeScale(0.5, 0.5);

    AVAudioSession *session = [AVAudioSession sharedInstance];
    self.volume = session.outputVolume;
    [session setActive:YES error:nil];
    [session addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionNew context:nil];
    
    //初始化音频播放器
    NSError *playerError;
    NSURL *urlSound = [[NSURL alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"dudu" ofType:@"m4a"]];
    AVAudioPlayer *playerSound = [[AVAudioPlayer alloc] initWithContentsOfURL:urlSound error:&playerError];
    playerSound.numberOfLoops = -1;//无限播放
    _player = playerSound;
    
    if (!self.player.isPlaying){
        [self.player play];
    }
    
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    [self becomeFirstResponder];
}

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
//     if (receivedEvent.type == UIEventTypeRemoteControl){
//         switch (receivedEvent.subtype) {
//             case UIEventSubtypeRemoteControlPause:{
//                 UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"暂停"message:@"测试" preferredStyle:UIAlertControllerStyleAlert];
//                 [self presentViewController:alertController animated:YES completion:nil];
//
//                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                     [alertController dismissViewControllerAnimated:true completion:^{
//
//                     }];
//                 });
//             }
//                 break;
//             case UIEventSubtypeRemoteControlTogglePlayPause:{
//                 if (self.player.isPlaying){
//                     self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handTime) userInfo:nil repeats:YES];
//                     //如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
//                     [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];
//                     [self.player stop];
//                 }else{
//                     [self handown:nil];
//                 }
//
//             }
//                 break;
//
//             case UIEventSubtypeRemoteControlPreviousTrack:
//
//                 break;
//             case UIEventSubtypeRemoteControlNextTrack:
//                 break;
//             default:
//                 break;
//         }
//  }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqual:@"outputVolume"]) {
        float newValue = [[change objectForKey:@"new"] floatValue];
         if (newValue - self.volume >= 0){
            NSLog(@"+");
             if (!self.timer){
                 self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handTime) userInfo:nil repeats:YES];
                 //如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
                 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];
                 [self.player stop];
             }
        }else{
            NSLog(@"_");
            if (self.volume != 1){
                [self.player stop];
                [self handown:nil];
            }
        }
        self.volume = newValue;
    }
}

- (void)handTime{
    self.time += 1;
    self.statusLabel.text = [self timeFormatted:self.time];
}

- (NSString *)timeFormatted:(int)totalSeconds{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    if (hours > 0){
        return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
    }else{
        return [NSString stringWithFormat:@"%02d:%02d",minutes,seconds];
    }
}
 

- (IBAction)mt:(id)sender {
    self.isMT = !_isMT;
    self.bgImageView.image = [UIImage imageNamed:self.isMT?@"icon15.png":@"icon14.png"];
}
- (IBAction)callTelphone:(id)sender {
    [UIView animateKeyframesWithDuration:0.5 delay:0 options:0 animations:^{
        self.telphoneBgView.hidden = NO;
        self.callTelPhoneButton.hidden = YES;
        self.muteButton.hidden = YES;
        [self resetTelphoneNumberHidden:NO];
//        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(0.5, 0.5);
//        }];
//        [UIView addKeyframeWithRelativeStartTime:1/3.0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(0.8, 0.8);
//        }];
//        [UIView addKeyframeWithRelativeStartTime:2/3.0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(1, 1);
//        }];
    } completion:nil];
}
- (IBAction)hiddenTelphone:(id)sender {
    [UIView animateKeyframesWithDuration:0.5 delay:0 options:0 animations:^{
//        [UIView addKeyframeWithRelativeStartTime:0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(1, 1);
//        }];
//        [UIView addKeyframeWithRelativeStartTime:1/3.0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(0.8, 0.8);
//        }];
//        [UIView addKeyframeWithRelativeStartTime:2/3.0 relativeDuration:1/3.0 animations:^{
//            self.telphoneBgImageView.transform = CGAffineTransformMakeScale(0.5, 0.5);
//        }];
        self.telphoneBgView.hidden = YES;
        self.callTelPhoneButton.hidden = NO;
        self.muteButton.hidden = NO;
        [self resetTelphoneNumberHidden:YES];
        self.phoneNumberLabel.text = self.telphoneNumber;
    } completion:nil];
}

- (void)isViewAddButton:(NSString *)add{
    if ([self.phoneNumberLabel.text isEqualToString:self.telphoneNumber]){
        self.phoneNumberLabel.text = @"";
    }
    NSString *txt = self.phoneNumberLabel.text;
    NSString *addText = [NSString stringWithFormat:@"%@",add];
    self.phoneNumberLabel.text = [txt stringByAppendingString:addText];
}

- (IBAction)callTelphoneNumber:(id)sender {
    [self resetTelphontNumber];
    NSInteger tag = [sender tag];
    switch (tag) {
        case 0:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber0.hidden = NO;
                self.callTelphoneNumber0.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber0 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"0"];
                    [self resetTelphontNumber];
                }
            }];
        }
            break;
        case 1:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber1.hidden = NO;
                self.callTelphoneNumber1.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber1 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"1"];
                    [self resetTelphontNumber];
                }
            }];
        }
            break;
        case 2:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber2.hidden = NO;
                self.callTelphoneNumber2.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber2 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"2"];
                    [self resetTelphontNumber];
                }
            }];
            
        }
            break;
        case 3:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber3.hidden = NO;
                self.callTelphoneNumber3.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber3 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"3"];
                    [self resetTelphontNumber];
                }
            }];
        }
            break;
        case 4:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber4.hidden = NO;
                self.callTelphoneNumber4.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber4 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"4"];
                    [self resetTelphontNumber];
                }
            }];
            
        }            break;
        case 5:
        {         [UIView animateWithDuration:0.3 animations:^{
            self.callTelphoneNumber5.hidden = NO;
            self.callTelphoneNumber5.backgroundColor = UIColor.whiteColor;
            [self.callTelphoneNumber5 setAlpha:0.3];
        }completion:^(BOOL finished) {
            if (finished){
                [self isViewAddButton:@"5"];
                [self resetTelphontNumber];
            }
        }];
            
            
        }               break;
        case 6:{
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber6.hidden = NO;
                self.callTelphoneNumber6.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber6 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"6"];
                    [self resetTelphontNumber];
                }
            }];
            
        }
            break;
        case 7:
        {         [UIView animateWithDuration:0.3 animations:^{
            self.callTelphoneNumber7.hidden = NO;
            self.callTelphoneNumber7.backgroundColor = UIColor.whiteColor;
            [self.callTelphoneNumber7 setAlpha:0.3];
        }completion:^(BOOL finished) {
            if (finished){
                [self isViewAddButton:@"7"];
                [self resetTelphontNumber];
            }
        }];
            
            
        }               break;
        case 8:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber8.hidden = NO;
                self.callTelphoneNumber8.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber8 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"8"];
                    [self resetTelphontNumber];
                }
            }];
            
        }            break;
        case 9:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber9.hidden = NO;
                self.callTelphoneNumber9.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber9 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"9"];
                    [self resetTelphontNumber];
                }
            }];
            
        }            break;
        case 10:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber10.hidden = NO;
                self.callTelphoneNumber10.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber10 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"*"];
                    [self resetTelphontNumber];
                }
            }];
            
        }            break;
        case 11:
        {
            [UIView animateWithDuration:0.3 animations:^{
                self.callTelphoneNumber11.hidden = NO;
                self.callTelphoneNumber11.backgroundColor = UIColor.whiteColor;
                [self.callTelphoneNumber11 setAlpha:0.3];
            }completion:^(BOOL finished) {
                if (finished){
                    [self isViewAddButton:@"#"];
                    [self resetTelphontNumber];
                }
            }];
            
        }            break;
        default:
            break;
    }
    
    
}

- (void)resetTelphontNumber{
    self.callTelphoneNumber1.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber2.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber3.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber4.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber5.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber6.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber7.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber8.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber9.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber10.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber11.backgroundColor = UIColor.clearColor;
    self.callTelphoneNumber0.backgroundColor = UIColor.clearColor;

}

- (void)resetTelphoneNumberHidden:(BOOL)isHidden{
    self.callTelphoneNumber1.hidden = isHidden;
    self.callTelphoneNumber2.hidden = isHidden;
    self.callTelphoneNumber3.hidden = isHidden;
    self.callTelphoneNumber4.hidden = isHidden;
    self.callTelphoneNumber5.hidden = isHidden;
    self.callTelphoneNumber6.hidden = isHidden;
    self.callTelphoneNumber7.hidden = isHidden;
    self.callTelphoneNumber8.hidden = isHidden;
    self.callTelphoneNumber9.hidden = isHidden;
    self.callTelphoneNumber10.hidden = isHidden;
    self.callTelphoneNumber11.hidden = isHidden;
    self.callTelphoneNumber0.hidden = isHidden;
}
- (IBAction)inComingUp:(id)sender {
    self.icon20ImageView.hidden = YES;
    self.icon14ImageView.hidden = NO;
    if (!self.timer){
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handTime) userInfo:nil repeats:YES];
        //如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];
        [self.player stop];
        if (self.statusLabel.hidden){
            self.statusLabel.hidden = NO;
        }
    }
}

- (IBAction)inComingDown:(id)sender {
    tellCallModel *call = [[tellCallModel alloc] init];
    NSArray *list = [tellCallModel retrieveArray];
    call.tID = [NSString stringWithFormat:@"%lu",list.count + 1];
    call.time = self.statusLabel.text;
    call.phone = self.telphoneNumber;
    call.address = @"电话";
    call.dian = @"来电";
    call.timeInterval = [self timeInterval];
    call.dateTime = [self dateTime];
    call.totalSeconds = [NSString stringWithFormat:@"%d",self.time];
    call.isCallIn = @"1";
    [call addToDB];
    RE_SINGLETON(CallTelphoneManager).isCalling = NO;
    [self dismissViewControllerAnimated:NO completion:^{
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        [session removeObserver:self forKeyPath:@"outputVolume"];
    }];
}


@end
